<template>
  <div class="workorder-container">
    <div class="header-section">
      <div class="title-actions">
        <h1 class="page-title">工单管理</h1>
        <el-button icon="Back" @click="goToDashboard" plain>返回首页</el-button>
      </div>
      <el-button type="primary" @click="handleCreate">新建工单</el-button>
    </div>
    
    <!-- 搜索筛选区 -->
    <div class="search-section">
      <el-card class="filter-card">
        <el-form :model="queryParams" ref="searchForm" :inline="true" size="large">
          <el-form-item label="关键词" label-width="80px">
            <el-input v-model="queryParams.keyword" placeholder="标题/内容" clearable style="width: 220px;" />
          </el-form-item>
          
          <el-form-item label="工单状态" label-width="80px">
            <el-select 
              v-model="queryParams.statusId" 
              placeholder="全部状态" 
              clearable
              style="width: 160px;"
            >
              <el-option 
                v-for="item in statusOptions" 
                :key="item.id" 
                :label="item.name" 
                :value="item.id"
              >
                <div class="select-option">
                  <el-tag 
                    :type="getStatusType(item.id)" 
                    effect="light" 
                    size="small"
                  >{{ item.name }}</el-tag>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="工单类型" label-width="80px">
            <el-select 
              v-model="queryParams.typeId" 
              placeholder="全部类型" 
              clearable
              style="width: 160px;"
            >
              <el-option 
                v-for="item in typeOptions" 
                :key="item.id" 
                :label="item.name" 
                :value="item.id" 
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="优先级" label-width="80px">
            <el-select 
              v-model="queryParams.priority" 
              placeholder="全部优先级" 
              clearable
              style="width: 120px;"
            >
              <el-option :value="1" label="低">
                <el-tag type="info" effect="light" size="small">低</el-tag>
              </el-option>
              <el-option :value="2" label="中">
                <el-tag effect="light" size="small">中</el-tag>
              </el-option>
              <el-option :value="3" label="高">
                <el-tag type="warning" effect="light" size="small">高</el-tag>
              </el-option>
              <el-option :value="4" label="紧急">
                <el-tag type="danger" effect="light" size="small">紧急</el-tag>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 已选条件标签 -->
        <div v-if="hasSelectedFilters" class="selected-filters">
          <span class="filter-label">已选条件：</span>
          <el-tag
            v-if="queryParams.statusId"
            closable
            @close="queryParams.statusId = null; handleSearch()"
            class="filter-tag"
          >
            状态: {{ getStatusName(queryParams.statusId) }}
          </el-tag>
          <el-tag
            v-if="queryParams.typeId"
            closable
            @close="queryParams.typeId = null; handleSearch()"
            class="filter-tag"
          >
            类型: {{ getTypeName(queryParams.typeId) }}
          </el-tag>
          <el-tag
            v-if="queryParams.priority"
            closable
            @close="queryParams.priority = null; handleSearch()"
            class="filter-tag"
          >
            优先级: {{ getPriorityText(queryParams.priority) }}
          </el-tag>
          <el-tag
            v-if="queryParams.keyword"
            closable
            @close="queryParams.keyword = ''; handleSearch()"
            class="filter-tag"
          >
            关键词: {{ queryParams.keyword }}
          </el-tag>
        </div>
      </el-card>
    </div>
    
    <!-- 工单列表 -->
    <div class="table-section">
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <span>工单列表</span>
            <div class="header-operations">
              <el-button :icon="Refresh" circle @click="getList" />
            </div>
          </div>
        </template>
        
        <el-table
          v-loading="loading"
          :data="workOrderList"
          border
          style="width: 100%"
          :header-cell-style="{ 
            background: '#f5f7fa', 
            fontSize: '14px', 
            color: '#333', 
            fontWeight: '500',
            padding: '12px 0',
            height: '46px'
          }"
          :cell-style="{
            padding: '8px 0', 
            fontSize: '14px'
          }"
          :row-style="{
            height: '52px'
          }"
        >
          <el-table-column type="index" width="60" label="序号" align="center" />
          
          <el-table-column prop="orderNo" label="工单编号" width="150" />
          <el-table-column prop="title" label="标题" min-width="180" align="center" show-overflow-tooltip />
          
          <el-table-column prop="statusName" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag 
                :type="getStatusType(scope.row.statusId)" 
                effect="plain"
                size="default"
                class="status-tag"
                round
              >
                {{ scope.row.statusName || '未知状态' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="typeName" label="类型" width="100" align="center">
            <template #default="scope">
              <el-tag 
                type="success" 
                effect="plain" 
                size="default"
                class="type-tag"
                round
              >
                {{ scope.row.typeName || '未知类型' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="priority" label="优先级" width="90" align="center">
            <template #default="scope">
              <el-tag 
                :type="getPriorityType(scope.row.priority)"
                effect="plain"
                size="default"
                round
                class="priority-tag"
              >
                {{ getPriorityText(scope.row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="creatorName" label="创建人" width="100" align="center" />
          
          <el-table-column prop="createTime" label="创建时间" width="160" align="center" />
          
          <el-table-column label="操作" width="140" align="center" fixed="right">
            <template #default="scope">
              <div class="operation-buttons">
                <el-button size="small" @click="handleView(scope.row)" type="primary" plain>查看</el-button>
                <el-button size="small" @click="handleEdit(scope.row)" type="primary" plain>编辑</el-button>
                <el-button size="small" type="danger" plain v-if="hasDeletePermission" @click="handleDelete(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, ArrowDown, Back } from '@element-plus/icons-vue'
import { workOrder as workOrderApi } from '@/api'

export default {
  name: 'WorkOrderList',
  setup() {
    const router = useRouter()
    const searchForm = ref(null)
    
    // 查询参数
    const queryParams = reactive({
      pageNum: 1,
      pageSize: 10,
      keyword: '',
      statusId: null,
      typeId: null,
      priority: null
    })
    
    // 数据相关
    const loading = ref(false)
    const workOrderList = ref([])
    const total = ref(0)
    const statusOptions = ref([])
    const typeOptions = ref([])
    
    // 判断是否有已选条件
    const hasSelectedFilters = computed(() => {
      return queryParams.keyword || 
             queryParams.statusId !== null || 
             queryParams.typeId !== null || 
             queryParams.priority !== null
    })
    
    // 权限控制
    const hasDeletePermission = computed(() => {
      // TODO: 根据用户角色判断是否有删除权限
      return true
    })
    
    // 获取工单列表
    const getList = async () => {
      loading.value = true
      try {
        // 确保参数正确
        const params = {
          ...queryParams,
          pageNum: queryParams.pageNum || 1,
          pageSize: queryParams.pageSize || 10
        };
        
        // 移除值为null或undefined的属性
        Object.keys(params).forEach(key => {
          if (params[key] === null || params[key] === undefined || params[key] === '') {
            delete params[key];
          }
        });
        
        console.log('正在调用获取工单列表API，参数:', params);
        const res = await workOrderApi.getWorkOrderList(params)
        console.log('工单列表API响应:', res);
        
        if (res.data && res.data.code === 200 && res.data.data) {
          workOrderList.value = res.data.data.list || []
          total.value = res.data.data.total || 0
          console.log('成功获取工单列表，数量:', workOrderList.value.length);
          
          // 处理列表数据，添加优先级文本
          workOrderList.value.forEach(item => {
            // 确保状态和类型名称存在
            if (!item.statusName && item.statusId) {
              const status = statusOptions.value.find(s => s.id === item.statusId)
              item.statusName = status ? status.name : '未知状态'
            }
            
            if (!item.typeName && item.typeId) {
              const type = typeOptions.value.find(t => t.id === item.typeId)
              item.typeName = type ? type.name : '未知类型'
            }
            
            item.priorityText = getPriorityText(item.priority);
          });
        } else {
          console.error('API返回异常，状态码:', res.data?.code, '消息:', res.data?.message);
          ElMessage.error(res.data?.message || '获取工单列表失败');
        }
      } catch (error) {
        console.error('获取工单列表失败', error)
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
        }
        ElMessage.error('获取工单列表失败：' + (error.message || '未知错误'));
      } finally {
        loading.value = false
      }
    }
    
    // 获取状态选项
    const getStatusOptions = async () => {
      try {
        const res = await workOrderApi.getWorkOrderStatuses()
        if (res.data && res.data.code === 200) {
          statusOptions.value = res.data.data || []
          console.log('成功获取工单状态，数量:', statusOptions.value.length);
        }
      } catch (error) {
        console.error('获取工单状态列表失败', error)
        ElMessage.error('获取工单状态失败');
      }
    }
    
    // 获取类型选项
    const getTypeOptions = async () => {
      try {
        console.log('正在调用获取工单类型API...');
        const res = await workOrderApi.getWorkOrderTypes()
        console.log('工单类型API响应:', res);
        if (res.data && res.data.code === 200) {
          typeOptions.value = res.data.data || []
          console.log('成功获取工单类型，数量:', typeOptions.value.length);
        } else {
          console.error('API返回异常，状态码:', res.data?.code, '消息:', res.data?.message);
          ElMessage.error('获取工单类型失败');
        }
      } catch (error) {
        console.error('获取工单类型列表失败', error)
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
        }
        ElMessage.error('获取工单类型失败');
      }
    }
    
    // 获取状态名称
    const getStatusName = (statusId) => {
      const status = statusOptions.value.find(item => item.id === statusId)
      return status ? status.name : '未知状态'
    }
    
    // 获取类型名称
    const getTypeName = (typeId) => {
      const type = typeOptions.value.find(item => item.id === typeId)
      return type ? type.name : '未知类型'
    }
    
    // 搜索
    const handleSearch = () => {
      queryParams.pageNum = 1
      getList()
    }
    
    // 重置
    const handleReset = () => {
      searchForm.value.resetFields()
      queryParams.pageNum = 1
      getList()
    }
    
    // 每页条数改变
    const handleSizeChange = (val) => {
      queryParams.pageSize = val
      getList()
    }
    
    // 页码改变
    const handleCurrentChange = (val) => {
      queryParams.pageNum = val
      getList()
    }
    
    // 新建工单
    const handleCreate = () => {
      router.push('/workorder/create')
    }
    
    // 返回首页
    const goToDashboard = () => {
      router.push('/dashboard')
    }
    
    // 查看工单详情
    const handleView = (row) => {
      router.push(`/workorder/${row.id}`)
    }
    
    // 编辑工单
    const handleEdit = (row) => {
      router.push(`/workorder/edit/${row.id}`)
    }
    
    // 处理下拉菜单命令
    const handleCommand = (command, row) => {
      if (command === 'delete') {
        handleDelete(row);
      }
    }
    
    // 删除工单
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除工单 ${row.orderNo} 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const res = await workOrderApi.deleteWorkOrder(row.id)
          if (res.data && res.data.code === 200) {
            ElMessage.success('删除成功')
            getList()
          } else {
            ElMessage.error(res.data.message || '删除失败')
          }
        } catch (error) {
          console.error('删除工单失败', error)
          ElMessage.error('删除工单失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 获取状态类型
    const getStatusType = (statusId) => {
      // 根据状态ID返回不同类型
      const statusMap = {
        1: 'info',    // 待处理
        2: 'warning', // 处理中
        3: 'primary', // 待反馈
        4: 'warning', // 待验收
        5: 'success', // 已完成
        6: 'info',    // 已关闭
        7: 'danger'   // 已取消
      }
      return statusMap[statusId] || 'info'
    }
    
    // 获取优先级文本
    const getPriorityText = (priority) => {
      const textMap = {
        1: '低',
        2: '中',
        3: '高',
        4: '紧急'
      }
      return textMap[priority] || '未知'
    }
    
    // 获取优先级类型
    const getPriorityType = (priority) => {
      const priorityMap = {
        1: 'info',    // 低
        2: '',        // 中
        3: 'warning', // 高
        4: 'danger'   // 紧急
      }
      return priorityMap[priority] || ''
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      getStatusOptions()
      getTypeOptions()
      getList()
    })
    
    return {
      searchForm,
      queryParams,
      loading,
      workOrderList,
      total,
      statusOptions,
      typeOptions,
      hasSelectedFilters,
      hasDeletePermission,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleCreate,
      handleView,
      handleEdit,
      handleDelete,
      handleCommand,
      getStatusType,
      getPriorityType,
      getPriorityText,
      getStatusName,
      getTypeName,
      getList,
      goToDashboard,
      Refresh,
      ArrowDown,
      Back
    }
  }
}
</script>

<style scoped>
/* 全局容器 */
.workorder-container {
  padding: 16px;
  background-color: #f9fafb;
  min-height: calc(100vh - 60px);
  width: 100%;
  box-sizing: border-box;
}

/* 标题区域 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.title-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  font-size: 28px;
  font-weight: 500;
  color: #262626;
  margin: 0;
  letter-spacing: -0.5px;
}

/* 搜索筛选区 */
.search-section {
  margin-bottom: 24px;
}

.filter-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: rgba(255, 255, 255, 0.95);
  padding: 10px;
}

/* 已选条件样式 */
.selected-filters {
  margin-top: 16px;
  padding-top: 10px;
  border-top: 1px dashed #eaeaea;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.filter-label {
  color: #606266;
  margin-right: 10px;
  font-size: 14px;
}

.filter-tag {
  margin-right: 8px;
  margin-bottom: 6px;
}

/* 下拉选择器内容格式 */
.select-option {
  display: flex;
  align-items: center;
  height: 30px;
}

/* 表格区域 */
.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: rgba(255, 255, 255, 0.95);
  width: 100%;
  margin: 0;
}

.table-section {
  width: 100%;
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

/* 分页区域 */
.pagination-container {
  padding: 15px 0;
  text-align: right;
}

/* 展开行样式 */
.expanded-row {
  padding: 16px;
  background-color: #f9fafb;
  border-radius: 8px;
  margin: 8px 16px;
  border: 1px solid #ebeef5;
}

/* 标签样式 */
.status-tag {
  width: 70px;
  text-align: center;
  border-radius: 12px;
}

.status-tag.el-tag--success {
  color: #67c23a;
  background-color: #f0f9eb;
  border-color: #c2e7b0;
}

.status-tag.el-tag--warning {
  color: #e6a23c;
  background-color: #fdf6ec;
  border-color: #f5dab1;
}

.status-tag.el-tag--danger {
  color: #f56c6c;
  background-color: #fef0f0;
  border-color: #fbc4c4;
}

.type-tag {
  width: 80px;
  text-align: center;
  border-radius: 12px;
}

.priority-tag {
  width: 60px;
  text-align: center;
  border-radius: 12px;
}

/* 表格动画和布局 */
.el-table {
  transition: all 0.3s ease;
  --el-table-header-bg-color: #f5f7fa;
  --el-table-border-color: #ebeef5;
  --el-table-row-hover-bg-color: #f5f7fa;
  font-size: 14px;
  color: #333;
}

/* 表格边框和阴影 */
.el-table--border {
  border: 1px solid #ebeef5;
  border-bottom: none;
  border-right: none;
}

.el-table::before {
  display: none;
}

/* 使表格整体更紧凑并占满宽度 */
.table-card {
  padding: 0;
  width: 100%;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.el-card__body {
  padding: 0;
  width: 100%;
}

.el-card__header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

/* 操作按钮区域样式 */
.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: nowrap;
  gap: 5px;
}

.operation-buttons .el-button {
  margin: 0;
  padding: 4px 8px;
  min-height: 28px;
  font-size: 12px;
}

.operation-buttons .el-button.el-button--danger {
  margin-left: 0;
}

/* 表头和单元格样式 */
.el-table th.el-table__cell {
  padding: 12px 0;
  font-weight: bold;
  border-right: 1px solid #ebeef5;
}

.el-table .el-table__cell {
  padding: 0;
  border-bottom: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
}

/* 表格行高与间距 */
.el-table__row {
  height: 60px;
}

/* 确保表格占满整个容器宽度 */
.el-table {
  width: 100% !important;
  table-layout: fixed;
}

/* 表格单元格样式 */
.el-table .cell {
  padding: 0 8px;
  line-height: 23px;
}

/* 确保序号列居中 */
.el-table .el-table__cell.is-center .cell {
  justify-content: center;
}

/* 固定表头和行高 */
.el-table__header-wrapper {
  height: 50px;
}

.el-table__header .el-table__cell {
  height: 50px;
  background-color: #f5f7fa;
}
</style> 
 